<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 5                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) Man0sions                                              |
// +----------------------------------------------------------------------+

// $Id:$
/*
	全局类
*/
class Main {
    public function __construct() {
        $this->cache_dir = TMP_PATH . '/cache/';
    }

    public function debugMode($mode = false) {

        if (isDebugHost() && $mode) {


            $GLOBALS['_CFG']['google_translate'] = '';
            $GLOBALS['_CFG']['fb_comment'] = '';
            $GLOBALS['_CFG']['fb_init'] = '';
           // $GLOBALS['_CFG']['add_this'] = '';
            $GLOBALS['_CFG']['google_code'] = '';
            define('GOODS_DELETE_SHOW', '');
        } else {

            define('GOODS_DELETE_SHOW', ' and is_delete=0');
			return false;
			if($this->denyVisit())
			{
				header("location:http://google.com");
				exit();
			}
			$this->host301();
        }
    }
    //取得目录名称
    public function dirNames($file) {
        $dir = preg_replace("/\\\/", "/", dirname($file));
        $s = preg_replace("/" . preg_quote(ROOT_PATH, "/") . "/", "", $dir);
        return $s;
    }
    //路径格式化
    public function pathUix($path) {
        $path = preg_replace('#\\\#', "/", $path);
        $path = preg_replace('#//#', "/", $path);
        return $path;
    }
    //token act
    public function validToken() {
        if ((isset($_REQUEST['token']) && isset($_SESSION['token'])) && ($_REQUEST['token'] == $_SESSION['token'])) {
            $this->setToken($GLOBALS['act']);
            return true;
        }
        return false;
    }
    public function setToken($act = '') {
        $act = !empty($act) ? $act : $GLOBALS['cache_id'];
        $_SESSION['token'] = md5(USER_AGENT . $act);
    }
    //安全的请求
    public function safeRequest($arr) {
        foreach ($arr as $key => $val) {
            if (is_array($val)) {
                $this->safeRequest($val);
            } elseif (is_string($val)) {
                $val = $this->safeValue($val);
            }
            $arr[$key] = $val;
        }
        return $arr;
    }
    public function safeValue($value) {
        $value = trim($value);
        if (get_magic_quotes_gpc()) {
            $value = stripslashes($value);
        }
        if (function_exists("mysql_real_escape_string")) {
            $value = $this->escapeString($value);
        } else {
            $value = addslashes($value);
        }
        return $value;
    }
    //取得安全的POST数据
    public function getPostData($data, $unset = array()) {

        $res = array();
        foreach ($data as $key => $val) {
            if (in_array($key, $unset)) {
                continue;
            }
			if(is_array($val))
			{
				 $res[$key] = $this->getPostData($val);
			}
			else
			{

				$res[$key] = $this->unescape($val);
			}
        }

        return $res;
    }
    public function unescape($str) {
        $str = rawurldecode($str);
        preg_match_all("/(?:%u.{4})|.{4};|&#\d+;|.+/U", $str, $r);
        $ar = $r[0];
        foreach ($ar as $k => $v) {
            if (substr($v, 0, 2) == "%u") {
                $ar[$k] = iconv("UCS-2", "utf-8//IGNORE", pack("H4", substr($v, -4)));
            } elseif (substr($v, 0, 3) == "") {
                $ar[$k] = iconv("UCS-2", "utf-8", pack("H4", substr($v, 3, -1)));
            } elseif (substr($v, 0, 2) == "&#") {
                $ar[$k] = iconv("UCS-2", "utf-8", pack("n", substr($v, 2, -1)));
            }
        }
        $res = join("", $ar);
		return $res;
    }
    //设置缓存
    public function cacheName($name) {
        $file_name = $this->cache_dir . $name . '-' . md5($name);
        return $file_name;
    }
    public function isCached($data_id, $life_time = 3600) {
        if (defined('NO_CACHE')) {

            return false;
        }
        $file_name = $this->cacheName($data_id);
        $res = true;
        if (file_exists($file_name)) {
            $sub = time() - filemtime($file_name);
            if ($sub >= $life_time) {
                $res = false;
            }
        } else {
            $res = false;
        }
        return $res;
    }
    public function getCache($data_id) {
        $file_name = $this->cacheName($data_id);
        if (file_exists($file_name)) {
            include_once ($file_name);
            return $$data_id;
        }
        return false;
    }
    public function setCache($data, $data_id) {
        unlink($this->cacheName($data_id));
        $str = var_export($data, true);
        $str = '<?php $' . $data_id . '=' . preg_replace("/\n/", "", $str) . ' ?>';
        file_put_contents($this->cacheName($data_id) , $str);
        return $data;
    }
    public function cached($key,$data){
		 $res = $this->isCached($key) ? $this->getCache($key) : $this->setCache($data , $key);
		 return $res;


    }
    //分配公共变量
    public function common() {
        /* 载入系统参数 */
        $sm = $GLOBALS['sm'];
        if (!defined('USER_AGENT')) define('USER_AGENT', $this->userAgent());
		$GLOBALS['_CFG']['thumb_size'] = isset($GLOBALS['_CFG']['thumb_size']) ? preg_split("/\*/",$GLOBALS['_CFG']['thumb_size']): array(250,250);


        //$sm->assign('t_cart', $GLOBALS['Order']->getTopCart());
      //  $order10 = $this->isCached('order10') ? $this->getCache('order10') : $this->setCache($GLOBALS['Order']->topOrder(0, 6) , 'order10');
       // $sm->assign('order10', $order10);
        //$goods10 = $this->isCached('goods10') ? $this->getCache('goods10') : $this->setCache($GLOBALS['Goods']->newGoods(0, 6) , 'goods10');
      //  $sm->assign('goods10', $goods10);
       // $news = $this->isCached('news') ? $this->getCache('news') : $this->setCache($GLOBALS['Cate']->catArticles(0, 6, ' where cat_id=2 ') , 'news');
       // $sm->assign('news', $news);
       // $recs = $this->isCached('recs') ? $this->getCache('recs') : $this->setCache($GLOBALS['Cate']->catArticles(0, 6, ' where cat_id=3 ') , 'recs');
       // $sm->assign('recent_shipping', $recs);


      // $GLOBALS['categories'] = $categories = $this->isCached('categories') ? $this->getCache('categories') : $this->setCache($GLOBALS['Cate']->categoryTree(0,true,true) , 'categories');

       // $sm->assign('categories', $categories);

		//$rec_search = $this->recentSearch();

		//$sm->assign('rec_search', $rec_search);


		//$rec_list = $GLOBALS['Goods']->recentGoods();




		//print_r($rec_list);
		//die();
		//$sm->assign('rec_list',	$rec_list);

		$GLOBALS['counts'] = $counts = $this->statCounts();
		$sm->assign('counts',	$counts);

        $keys = $this->isCached('keys') ? $this->getCache('keys') : $this->setCache($this->hotKeywords(0, 6) , 'keys');
        $sm->assign('keys', $keys);
        $sm->assign('cfg', $GLOBALS['_CFG']);
        //$sm->assign('lang', $GLOBALS['_LANG']);
        $sm->assign('session', $_SESSION);
        //$sm->assign('S', $_SESSION);
        $sm->assign('act', $GLOBALS['act']);
        $sm->assign('height', $GLOBALS['height']);
        $sm->assign('width', $GLOBALS['width']);
        $sm->assign('ipt', $GLOBALS['ipt']);
        $sm->assign('no_style', $GLOBALS['no_style']);
        $sm->assign('onclick', $GLOBALS['onclick']);
        if (!isset($_SESSION['price_type'])) {
            $_SESSION['price_type'] = "USD";
        }
        if (!isset($_SESSION['user_id'])) {
            $_SESSION['user_id'] = 0;
            $_SESSION['user_name'] = '';
        }

        $sm->assign("t_path",  $GLOBALS['temp_dir']);

        $sm->assign("s_path", $GLOBALS['_SEP'] . "/includes/static");
        $sm->assign('token', $this->setToken());
        $ua = @$_SESSION[USER_AGENT];
        $sm->assign('sess_agent', @$ua);
        $sm->assign('sep', $GLOBALS['_SEP']);
        //判断用户是否有未完成的订单，如果有则调出购物车和地址
        $sess_id = @$_COOKIE['ETH_SESS'];
        if ($sess_id) {
            //$GLOBALS['Order']->unOrder($sess_id);
        }

    }
    //url301跳转
    public function url301($url) {
		if($GLOBALS['no_style'])
		{
			return false;
		}
        if (!preg_match("/" . $url . "/", $_SERVER['REQUEST_URI'], $arr)) {
            header("HTTP/1.1 301 Moved Permanently");
            header("location:" . $url . "");
            exit();
        }
    }
    //主机跳转
    public function host301() {
        $shop_name = $GLOBALS['_CFG']['shop_name'];
        $host = $_SERVER['HTTP_HOST'];
        preg_match("#" . $host . "#i", $shop_name, $m);
        if (!$m) {
            $url = 'http://' . $shop_name . $_SERVER['REQUEST_URI'];
            header("HTTP/1.1 301 Moved Permanently");
            header("location:" . $url . "");
            exit();
        }
    }
    //加载配置
    public function loadConfig($cache = true) {
        $sql = "select * from config";
        $data = $GLOBALS['db']->getAll($sql);
        if ($cache) {
            $arr = array();
            foreach ($data as $key => $val) {
                $code = $val['code'];
                if ($val['value_type'] == 'json') {
                    $val['value'] = $this->json2Array($val['value']);
                }
                $arr[$code] = $val['value'];
            }
            //$config = var_export($arr);
            return $arr;
        }
        return $data;
    }
    //修改配置
    public function editConfig($data) {
        foreach ($data as $key => $val) {
            $sql = "update config set `value`='" . $this->escapeString($val) . "' where `code`='" . $key . "'; ";
            $res[] = mysql_query($sql);

        }
        if (array_sum($res) == count($res)) {
            return true;
        } else {
            return false;
        }
    }
    //日期格式化
    function dateFormat($date, $format = 'Y-m-d H:i:s') {
        if ($date) {
            return date($format, $date);
        } else {
            return '';
        }
    }
    public function escapeString($str) {

        return mysql_real_escape_string(trim($str));
    }
	//过滤数据
	function strips($data) {
       $arr = array();
	   if(!is_array($data))
		{
			return stripcslashes($data);

	    }
        foreach ($data as $key => $val) {
            if (is_array($val)) {
                $arr[$key] = $this->strips($val);
            } else {
                $arr[$key] = stripcslashes(($val));
            }
        }
        return $arr;
    }
    //json2array
    function json2Array($json) {
        $json = @json_decode($json) ? @json_decode($json) : $json;
        $arr = array();
        foreach ($json as $key => $val) {
            if (is_object($val)) {
                $arr[$key] = $this->json2Array($val);
            } else {
                $arr[$key] = @$this->escapeString(trim($val));
            }
        }
        return $arr;
    }
	function array2Json($arr,$filter=true) {
        $json = json_encode($arr);
		if($filter)
			$json = $this->escapeString($json);

        return $json;
    }
    //构建url
    function buildUri($name, $id = 0, $type = '') {

        $name = substr(ucwords($name) , 0, 80);

        $name = preg_replace('/[^\w -]/', '', $name);
        $name = preg_replace('/ +/', '-', $name);
        $name = trim($name);
        $name = trim($name, "-");
        $name = preg_replace('/\-+/', '-', $name);
        //$name = preg_replace('/-\w{1,3}$/', '', $name);

        if ($id < 0) return $name;
        $name = $name ? $name : 'page';
        if ($type) {
            if (preg_match("/\?/", $type)) {
                return sprintf('%s&page=%s', $type, $id);
            } else {
                return sprintf('%s-%s-%s.html', $type, $id, $name);
            }
        } else {
            return sprintf('%s', $id);
        }
    }
    //构造翻页
    function pager($count, $size, $type, $name = '', $l_r = true) {
        $page = isset($GLOBALS['page']) ? intval($GLOBALS['page']) : 0;
       // $type = preg_replace("/ +/", "-", $type);
        $list = array();
        $amount = ceil($count / $size);
        $left = $page - 3;
        $right = $page + 3;
        for ($i = 0; $i < $amount; $i++) {
            if ($l_r) {
                if ($left >= 0) {
                    if ($i >= $left && $i <= $right) {
                        $list[$i] = $this->buildUri($name, $i, $type);
                    }
                } else {
                    if ($i <= 6) {
                        $list[$i] = $this->buildUri($name, $i, $type);
                    }
                }
            } else {
                $list[] = $this->buildUri($name, $i, $type);
            }
        }

        $pager['first'] = @$this->buildUri($name, 0, $type);
        $pager['last'] = @$this->buildUri($name, $amount - 1, $type);
		$pager['next'] = @$list[($page+1)];
		$pager['prev'] = @$list[($page-1)];
        $pager['list'] = $list;
        $pager['page'] = $page;
        $pager['total'] = $amount;
        $pager['count'] = $count;
		//print_r($pager);
        return $pager;
    }
    //定时发布文章
    public function cronArticle() {
        $limit = 24 * 3600;
        $prev = $GLOBALS['db']->getOne("select max(add_time) from article");
        if (abs(time() - $prev) > $limit) {
            $sql = "select add_time,article_id from article where is_open=0";
            $arr = $GLOBALS['db']->getRow($sql);

            $n_id = !empty($arr['article_id']) ? intval($arr['article_id']) : 0;
            $sql = "update article set is_open=1,add_time=" . time() . " where article_id=$n_id";
            @mysql_query($sql);
        }
    }
    //定时发商品
    public function cronGoods() {
        $limit = (rand(24, 72) * 3600);
        $goods = $GLOBALS['db']->getRow("select  max(add_time) as  add_time,goods_id from goods where  1 order by goods_id desc");
        $sub = abs(time() - $goods['add_time']);

        if ($sub > $limit) {
            $sql1 = "select goods_id from goods where is_delete=1 order by goods_id desc";
            $arr = $GLOBALS['db']->getRow($sql1);
			if(!empty($arr['goods_id']))
			{
				$sql = "update goods set add_time='" . time() . "' , is_delete=0 where goods_id='" . $arr['goods_id'] . "';";
				mysql_query($sql);
			}
        }
    }
    //热门搜索
    public function hotKeywords($start = 0, $size = 10) {
        $sql = "select  distinct  keyword from keywords where 1  limit $start,$size";
        $data = $GLOBALS['db']->getAll($sql);
        $keys = array();
        foreach ($data as $key => $val) {
            $kw = trim($val['keyword']);
            $keys[$key]['url'] = $this->buildUri($kw, '0', SEARCH);
            $keys[$key]['title'] = $kw;
        }
        return $keys;
    }
    //计算列表总数
    function counts($sql) {
        return $GLOBALS['db']->getOne($sql);
    }
    //取得默认省会
    public function getRegion($region_id) {
        $sql = "select region_id,region_name from region where parent_id='" . $region_id . "'";
        $data = $GLOBALS['db']->getAll($sql);
        return $data;
    }
    //取得地址名称
    public function getRegionOne($region_id) {
        $sql = "select region_name from region where region_id='" . $region_id . "'";
        $data = $GLOBALS['db']->getOne($sql);
        return $data;
    }
    //取得cookie收货人
    public function cookieAddr() {
        if (isset($_COOKIE['ETH_ADDR'])) {
            $addr = base64_decode($_COOKIE['ETH_ADDR']);
            return $addr;
        }
        return '';
    }
    //新增运费
    public function shippingAdd($data) {
        $sql = "insert into shipping(`config`) values ('" . $data . "')";
        return mysql_query($sql);
    }
    //修改运费
    public function shippingEdit($data, $shipping_id) {
        $sql = "update shipping set `config`='" . $data . "' where shipping_id=$shipping_id";
        return mysql_query($sql);
    }
    //取得shipping_list
    public function shippingList() {
        $sql = "select * from shipping  where 1";
        $data = $GLOBALS['db']->getAll($sql);
        foreach ($data as $key => $val) {
            $config = $this->json2Array($val['config']);
            $val['name'] = $config['name'];
            $val['base_fee'] = $config['base_fee'];
			$val['base_feed'] = $this->priceFormat($val['base_fee']);
            $val['free_money'] = $config['free_money'];
            $val['desc'] = $config['desc'];
            unset($val['config']);
            $data[$key] = $val;
        }
        return $data;
    }
    //取得一个运费方式
    public function shippingOne($shipping_id = 0) {
        $shipping_list = $this->shippingList();
        foreach ($shipping_list as $key => $val) {
            if ($val['shipping_id'] == $shipping_id) {
                return $val;
            }
        }
        return false;
    }
    //增加payment
    public function paymentAdd($data) {
        $arr = $this->json2Array(stripcslashes($data));
        $code = $arr['pay_code'];
        $sql = "insert into payment(`pay_code`,`config`) values('" . $code . "','" . $data . "')";
        return mysql_query($sql);
    }
    //修改payment
    public function paymentEdit($data, $pay_id) {
        $arr = $this->json2Array(stripcslashes($data));
        $code = $arr['pay_code'];
        $sql = "update payment set `pay_code`='" . $code . "',`config`='" . $data . "' where pay_id=$pay_id";
        return mysql_query($sql);
    }
    //取得payment_list
    public function paymentList() {
        $sql = "select * from payment ";
        $data = $GLOBALS['db']->getAll($sql);
        foreach ($data as $key => $val) {
            $config = $this->json2Array($val['config']);
            $val['pay_name'] = $config['pay_name'];
            $val['pay_desc'] = $config['pay_desc'];
            $val['account'] = $config['account'];
            $val['currency'] = $config['currency'];
            unset($val['config']);
            $data[$key] = $val;
        }
        return $data;
    }
    //取得一个payment
    public function paymentOne($pay_id) {
        $payment_list = $this->paymentList();
        foreach ($payment_list as $key => $val) {
            if ($val['pay_id'] == $pay_id) {
                return $val;
            }
        }
        return false;
    }
    //邮件服务器设置
    public function emailSetEdit($data) {
        $sql = "update config set value='" . $data . "' where code='email'";
        return mysql_query($sql);
    }
    //$this->priceFormat
    public function priceFormat($data) {
        if (is_array($data)) {
            foreach ($data as $key => $val) {
                $key1 = $key . 'd';
                $data[$key1] = $this->priceFormat2(floatval($val));
            }
            return $data;
        } elseif (is_numeric($data)) {
            return $this->priceFormat2($data);
        }
    }
    //货币格式化
    public function priceFormat2($price = 0) {
		return intval($price);
        $price_type = !empty($_SESSION['price_type']) ? $_SESSION['price_type'] : 'USD';
        //货币转换
        $price_sym = $GLOBALS['_CFG']['currency'];
        $sp = preg_split("/,/", $price_sym);
        if (count($sp) == 4) {
            foreach ($sp as $val) {
                $sps = preg_split("/:/", $val);
                $type = $sps[0];
                if ($price_type == $type) {
                    $sysm = $sps[1];
                    $price = $price * $sps[2];
                }
            }
        }
        $price = number_format($price, 2);
        //return sprintf($sysm, $price);

    }
    //设置position
    public function assigns($position) {

        $GLOBALS['sm']->assign('page_title', $position['title']);
        $GLOBALS['sm']->assign('description', $position['description']);
        $GLOBALS['sm']->assign('keywords', $position['keywords']);
        $GLOBALS['sm']->assign('ur_here', $position['ur_here']);
    }
    //构造当前位置
    function position($data = array() , $type = '') {
        $ur_here = "<a href='./' title='Home Page'>Home</a>";
        if ($type == GOODS_NAME) //商品内页
        {
            $title = !empty($data['title']) ? $data['title'] : $data['goods_name'];
            $title = $title . '-' . $data['goods_id'];
            $description = !empty($data['description']) ? $data['description'] : $title.' Online Shopping ';

            $keywords = !empty($data['keywords']) ? $data['keywords'] : '';//$data['goods_name'];
            $ur_here.= $this->urHere($data['cat_id'], 'category', CAT_NAME);
            $ur_here.= ' <code>&gt;</code> ' . $data['goods_name'];
        } elseif ($type == CAT_NAME) {
            $title = !empty($data['cat_name']) ? $data['cat_name'] : $data['title'];
            $title.= ' page-' . ($GLOBALS['page'] + 1);
            $description = !empty($data['cat_desc']) ? $data['cat_desc'] : $data['cat_name'];
            $keywords = !empty($data['keywords']) ? $data['keywords'] : $data['cat_name'];
            $ur_here.= $this->urHere($data['cat_id'], 'category', $type);
        } elseif ($type == CHECKOUT) {
            $title = 'One Step Checkout';
            $keywords = '';
            $description = '';
            $ur_here.= '<code>&gt;</code> ' . $title;
        } elseif ($type == ART) {
            $title = $data['title'];
            $description = !empty($data['description']) ? $data['description'] : $data['title'];
            $keywords = !empty($data['keywords']) ? $data['keywords'] : $data['title'];
            $ur_here.= $this->urHere($data['cat_id'], 'article_cat', ART_CAT);
            $ur_here.= ' <code>&gt;</code> ' . $data['title'];
        } elseif ($type == ART_CAT) {
            $title = !empty($data['title']) ? $data['title'] : $data['cat_name'];
            $title.= ' page-' . ($GLOBALS['page'] + 1);
            $description = !empty($data['cat_desc']) ? $data['cat_desc'] : $data['cat_name'];
            $keywords = !empty($data['keywords']) ? $data['keywords'] : $data['cat_name'];
            $ur_here.= $this->urHere($data['cat_id'], 'article_cat', $type);
        } elseif ($type == SEARCH) {

            $title = $this->setMeta($data, 'cat_title', $GLOBALS['page']);

            $keywords = $this->setMeta($data, 'cat_keywords');
            $description = $this->setMeta($data, 'cat_description',$GLOBALS['page']);

            $ur_here.= '<code>&gt;</code> search for : ' . $data;
        } else {
            $title = $GLOBALS['_CFG']['shop_title'];

            $description = $GLOBALS['_CFG']['shop_desc'];
            $keywords = $GLOBALS['_CFG']['shop_keywords'];
            $ur_here.= '<code>&gt;</code> ' . $type;
        }
        $arr['title'] = ucwords($title) . ' - ' . $GLOBALS['_CFG']['shop_name'];
        $arr['keywords'] = $keywords;
        $arr['description'] = $description;
        $arr['ur_here'] = $ur_here;

        return $arr;
    }
    //构建ur_here
    public function urHere($cat_id, $table, $type) {
        $f_ids = $this->fatherIds($cat_id, $table, $arr);
        krsort($f_ids);
        $str = '';
        foreach ($f_ids as $key => $val) {
            $cat_name = ucwords($val['cat_name']);
            $c_id = $val['cat_id'];
            $url = $this->buildUri($cat_name, $c_id, $type);
            $str.= "<code>&gt;</code><a href='$url' title='$cat_name'>$cat_name</a>";
        }
        return $str;
    }
    //取得上级分类
    public function fatherIds($cat_id, $table = 'category', &$arr) {
        $sql = "select cat_name,cat_id,parent_id from $table where cat_id=$cat_id";
        $data = $GLOBALS['db']->getRow($sql);
        $arr[] = $data;
        if ($data['parent_id'] > 0) {
            @$this->fatherIds($data['parent_id'], $table, $arr);
        }
        return $arr;
    }
    //set meta
    //设置keywords，description，title
    public function setMeta($str, $type, $pg = 0, $str1 = '') {


        $pg_str = $pg ? ' page-' . ($pg+1) . ' ' : '';
        $format_str = @$GLOBALS['_CFG'][$type];

        $shop_name = ''; // ucfirst($GLOBALS['_CFG']['shop_name']);
        if ($type == 'cat_title') {

			$res = @sprintf($format_str, $str, $str.$pg_str);


        } elseif ($type == 'cat_description') {

            $res = @sprintf($format_str, $str.$pg_str,  ucfirst($GLOBALS['_CFG']['shop_name']));


        } elseif ($type == 'goods_keywords') {

            $res = @sprintf($format_str, $str, $str, $str1);
        } else {
            $res = sprintf($format_str, $str, $str, $shop_name . $pg_str);
        }

        $res = ucwords($res);
        return $res;
    }
    //msg
    function msg($msg = '', $url, $back = false) {
        if (!$msg) {
            echo "<script>location.href='" . $url . "'</script>";
            exit();
        }
        if (!$back) {
            echo "<script>alert('" . $msg . "');location.href='" . $url . "'</script>";
            exit();
        } else {

            echo "<script>alert('" . $msg . "');history.back()</script>";
            exit();
        }
    }
    //设置优惠码
    public function setDiscount($val,$order_id=0) {
        $code = substr(md5(time() . USER_AGENT.$order_id) , 10, 10);
        $sql = "insert into discount(`code`,`value`,`add_time`,`order_id`) values('" . $code . "','" . $val . "','" . time() . "','".$order_id."');";
		//echo $sql."\n";
		//return false;
        $res = mysql_query($sql);
		$r = array();
		if($res)
		{
			$r['code'] = $code;
			$r['value'] = $val;
		}

        return $res;
    }
    //优惠码列表
    public function discountList($start = 0, $size = 20, $where = '') {
        $sql = "select * from discount $where  order by add_time desc limit $start,$size ";
        $data = $GLOBALS['db']->getAll($sql);
        foreach ($data as $key => $val) {
            $val['add_time'] = $this->dateFormat($val['add_time']);
            if ($val['use_info']) {
                $arr = $this->json2Array($val['use_info']);
                $arr['use_date'] = $this->dateFormat($arr['use_date']);
                $val['use_info'] = $arr;
                //$val['user'] =	$GLOBALS['User']->userInfo($arr['user_id']);

            }
            $data[$key] = $val;
        }
        return $data;
    }
    //取得一个优惠码
    public function discountOne($code) {
        $sql = "select * from discount where code='" . $code . "' and status=1;";
        $data = $GLOBALS['db']->getRow($sql);
        if ($data) {
            $data['valued'] = $this->priceFormat($data['value']);
        }
        return $data;
    }
    //删除优惠码
    public function delDiscount($discount_id) {
        $sql = "delete from discount where discount_id=$discount_id ";
        $res = mysql_query($sql);
        return $res;
    }
    //使用优惠码
    public function applyDiscount() {
        $discount = @$_SESSION[USER_AGENT]['discount'];
        $use['user_id'] = $_SESSION['user_id'];
        $use['order'] = @$_SESSION[USER_AGENT]['order'];
        $addr = $GLOBALS['User']->getAddr();
        $use['email'] = $addr['address']['email'];
        $use['use_date'] = '' . time() . '';
        $json = $this->escapeString(json_encode($use));
        $sql = "update discount set use_info='" . $json . "',status=2 where discount_id='" . $discount['discount_id'] . "'";
        mysql_query($sql);
    }
    //默认取网站域名作为水印
    public function waterMark($path) {
        //if($GLOBALS['_CFG']['debug']) return $path;
        if (!file_exists($path)) {
            return false;
        }
        $host = strtoupper($_SERVER['HTTP_HOST']);
        $img_info = @getimagesize($path);
        $path_info = pathinfo($path);
        $new_path = $path_info['dirname'] . '/' . substr($path_info['filename'], 0, 100) . substr(md5($path_info['filename']) , 0, 5) . '.' . $path_info['extension'];
        //$new_path2 = $path_info['dirname'].'/'.$path_info['filename'].md5($path_info['filename']).'.'.$path_info['extension'];
        //@unlink($new_path2);
        if (file_exists($new_path)) {
            //return $new_path;

        }
        //如果不能使用gd库则返回原始路径
        if (!$img_info) {
            return $path;
        }
        switch (strtolower($path_info['extension'])) {
            case 'jpg':
            case 'jpeg':
                $img = @imagecreatefromjpeg($path);
                break;

            case 'png':
                $img = @imagecreatefrompng($path);
                break;

            default:
                $img = false;
                break;
        }
        //只处理jpg和png图片，其他类型直接返回
        if (!$img) {
            return $path;
        }
        $font_path = STA_PATH . '/fonts/fonts.ttf';
        //如果字体不存在，返回原路径
        if (!file_exists($font_path)) {
            return $path;
        }
        //首先生成文字图片
        $font_width = strlen($host) * 20;
        $font_im = imagecreatetruecolor($font_width, 20);
        $font_bg = imagecolorallocate($font_im, 178, 178, 178); //背景颜色
        $x = ($img_info[0] - $font_width) * (4.5 / 5);
        $y = ($img_info[1]) * (4.5 / 5);
        imagettftext($img, 20, 0, $x, $y, $font_bg, $font_path, $host);
        //header("Content-type: image/jpeg");
        imagejpeg($img, $new_path);
        imagedestroy($img);
        return $new_path;
    }
    //缩略图生成 $path--原图路径,$per--缩略比例,可以传0.5，也可以传array($width,$height),$remove--是否删除原图
    function resizeImage($path, $per = 0.5, $remove = false) {
        $info = pathinfo($path);
        $new_path = @$info['dirname'] . '/t_' . @($info['filename']) . '.' . @$info['extension'];
        if (file_exists($new_path)) {
            return $new_path;
        }
        if (!file_exists($path)) {
            return false;
        }
        $size = @getimagesize($path);
        if (!$size) {
            return $path;
        }
        $width = $size[0];
        $height = $size[1];
        if (is_array($per)) {
            $new_width = $per[0];
            $new_height = $per[1];
        } else {
            $new_width = $width * $per;
            $new_height = $height * $per;
        }
        //创建画板
        $thumb = imagecreatetruecolor($new_width, $new_height);
        //获取图片
        switch ($size['mime']) {
            case 'image/png':
                $source = imagecreatefrompng($path);
                break;

            case 'image/gif':
                $source = imagecreatefromgif($path);
                break;

            case 'image/jpeg':
                $source = imagecreatefromjpeg($path);
                break;
        }
        if (function_exists('imagecopyresampled')) {
            imagecopyresampled($thumb, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        } else {
            imagecopyresized($thumb, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        }
        $new_path = strtolower($new_path);
        imagejpeg($thumb, $new_path);
        if ($remove) {
            unlink($path);
        }
        return $new_path;
    }
    //格式化路径名称
    function pathFormat($str) {
        $str = preg_replace("/[^\w\/\.]/", "-", $str);
        $str = preg_replace("/-{2,}/", "-", $str);
        return $str;
    }
    //文件上传
    function uploader($new_dir = './images/', $resize = true, $remove = true, $file_names = '', $type = 'Filedata',$swfupload=false) {
        if (!file_exists($new_dir)) {
            $this->mkdirs($new_dir);
        }
        if (!empty($_FILES)) {

            $tempFile = $_FILES[$type]['tmp_name'];
            $name = $_FILES[$type]['name'];
            $info = pathinfo($name);

            $md5 = md5($info['filename'] . time());
            if ($file_names) {
                $file_name = $file_names . '.' . strtolower($info['extension']);
            } else {
                $file_name = substr($md5, 0, 10) . '.' . strtolower($info['extension']);
            }
            $new_name = $new_dir . '' . $file_name; //上传后的图片路径
            //$fileTypes = array('jpg','jpeg','gif','png','pdf','doc','docx','xls','xlsx','mov','3gp','mp4'); //允许的文件后缀
            $imgTypes = array(
                'jpg',
                'jpeg'
            ); //只有jpg可以缩略图片类型
            move_uploaded_file($tempFile, $new_name);
            if (in_array($info['extension'], $imgTypes) && $resize) {
                $new_name = $this->resizeImage($new_name, $per = 0.5, $remove);
            }
            if (preg_match("/\/admin\//", $new_name)) $new_name = '../' . $new_name;
			//如果是swfupload
			if($swfupload)
			{
				$res['type'] = $info['extension'];
				$res['url'] = $new_name;
				$res['file_name'] = $name;
				return (json_encode($res));
			}

            return $new_name; //上传成功后返回给前端的数据

        } else {
            return false;
        }
    }
    //取得用户身份标识
    public function userAgent($par = 'ETH') {
        $ag = $_SERVER['HTTP_USER_AGENT'] . $_SERVER['SERVER_ADDR'] . $par;
        return md5($ag);
    }
    //二维数组根据某个键排序 $keys
    function array_sort($arr, $keys, $type = 'asc') {
        $keysvalue = $new_array = array();
        foreach ($arr as $k => $v) {
            $keysvalue[$k] = $v[$keys];
        }
        if ($type == 'asc') {
            asort($keysvalue);
        } else {
            arsort($keysvalue);
        }
        reset($keysvalue);
        foreach ($keysvalue as $k => $v) {
            $new_array[$k] = $arr[$k];
        }
        return $new_array;
    }
    //分割文件路径,解析文件名
    function splitFileName($str, $sep = ',', $host = false) {
        $sp = preg_split("/" . $sep . "/", $str);
        $data = array();
        foreach ($sp as $key => $val) {
            if ($val) {
                $file = preg_replace("/ /", "+", $val);
                $data[$key]['url'] = $file;
                if ($host) $data[$key]['url'] = preg_replace("/\.\//", $GLOBALS['host'] . '/', $file);
                $info = pathinfo($file);
                $data[$key]['name'] = base64_decode($info['filename']) . '.' . $info['extension'];
            }
        }
        return $data;
    }
    //取得邮件模板
    public function mailTemplate() {
        $sql = "SELECT * FROM mail_templates";
        return $GLOBALS['db']->GetAll($sql);
    }
    //取得一个邮件模板
    public function mailTemplateOne($code) {

        $sql = "SELECT * FROM mail_templates where code='" . $code . "'";
        $data = $GLOBALS['db']->GetRow($sql);

        $data['content'] = htmlspecialchars_decode($data['content']);
        return $data;
    }
    //删除一个邮件模板
    public function mailTemplateDel($t_id) {
        $sql = "delete from mail_templates where t_id=$t_id";
        return mysql_query($sql);
    }
    // mail init
    private function mailInit() {
        $conf = $this->loadConfig();
        $mail_conf = $conf['email'];

        require_once (INC_PATH . "/class/mail/class.phpmailer.php");
        $mail = new PHPMailer(); // create a new object
        $mail->IsSMTP(); // enable SMTP
        $mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
        $mail->SMTPAuth = true; // authentication enabled
        if ($mail_conf['smtp_ssl']) {
            $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail

        }
        $mail->Host = $mail_conf['smtp_server'];
        $mail->Port = $mail_conf['smtp_port'];
        $mail->Username = $mail_conf['account'];
        $mail->Password = $mail_conf['passwd'];
        $mail->SetFrom($mail_conf['account'], $conf['shop_name']);
        return $mail;
    }
    //发送邮件
    /*$info['subject'] = 'test mail!';
    $info['body'] = 'hello test!';
    $info['to'] = array('81434146@qq.com','2247525611@qq.com','1729908966@qq.com');//,'2247525611@qq.com','1729908966@qq.com'
    $info['files'] = array('index.php');
    */
    public function sendMail($info) {
        $to = is_array($info['to']) ? $info['to'] : array();
        $file = !empty($info['file']) && is_array($info['file']) ? $info['file'] : array();
        $mail = $this->mailInit();
        $mail->Subject = !empty($info['subject']) ? $info['subject'] : $GLOBALS['_CFG']['shop_name'];
        //$mail->Body = $info['body'];
        $mail->MsgHTML($info['body']);

        foreach ($to as $key => $val) //收件人可以是多个 $info['to'] = array('mail1@qq.com','mail12@qq.com','mail13@qq.com');
        {
            if (!$val) continue;
            $mail->AddAddress($val);
        }
        foreach ($file as $s_k => $s_v) {
            if (!$s_v) continue;
            $mail->AddAttachment($s_v);
        }
        if (!$mail->Send()) {
            return $mail->ErrorInfo;
        } else {
            return true;
        }
    }
    //设置翻页
    public function setPage($sql, $size = 10, $type = 'page', $name = 'p') {
        $pager = $this->pager($this->counts($sql) , $size, $type, $name);
       //print_r($pager);
        $GLOBALS['sm']->assign('pagers', $pager);
    }
    //网站地图
    public function sitemap() {
        $site_url = $GLOBALS['host'] . '/';
        $xml = "<\x3Fxml version=\"1.0\" encoding=\"UTF-8\"\x3F>\n<urlset xmlns=\"http://www.google.com/schemas/sitemap/0.84\">\n";
        $item = array(
            'loc' => "$site_url",
            'lastmod' => $this->dateFormat(time() , 'Y-m-d') ,
            'changefreq' => "hourly",
            'priority' => "0.9",
        );
        $xml.= $this->siteMapItem($item);
        foreach ($GLOBALS['Cate']->categoryAll() as $key => $val) {
            $item = array(
                'loc' => "$site_url" . $this->buildUri($val['cat_name'], $val['cat_id'], CAT_NAME) ,
                'lastmod' => $this->dateFormat(time() , 'Y-m-d') ,
                'changefreq' => "hourly",
                'priority' => "0.8",
            );
            $xml.= $this->siteMapItem($item);
        }
        $sql = "SELECT cat_id,cat_name FROM article_cat WHERE cat_id=1";
        $res = mysql_query($sql);
        while ($row = mysql_fetch_row($res, MYSQL_ASSOC)) {
            $item = array(
                'loc' => "$site_url" . $this->buildUri($row['cat_name'], $row['cat_id'], ART_CAT) ,
                'lastmod' => $this->dateFormat(time() , 'Y-m-d') ,
                'changefreq' => "hourly",
                'priority' => "0.8",
            );
            $xml.= $this->siteMapItem($item);
        }
        $sql = "SELECT goods_id, goods_name FROM goods WHERE is_delete = 0 ";
        $res = mysql_query($sql);
        while ($row = mysql_fetch_row($res, MYSQL_ASSOC)) {
            $item = array(
                'loc' => "$site_url" . $this->buildUri($row['goods_name'], $row['goods_id'], GOODS_NAME) ,
                'lastmod' => $this->dateFormat(time() , 'Y-m-d') ,
                'changefreq' => "weekly",
                'priority' => "0.7",
            );
            $xml.= $this->siteMapItem($item);
        }
        /* 文章 */
        $sql = "SELECT article_id,title, add_time FROM article WHERE is_open=1 and cat_id=2 ";
        $res = mysql_query($sql);
        while ($row = mysql_fetch_row($res, MYSQL_ASSOC)) {
            $article_url = $this->buildUri($row['title'], $row['article_id'], ART);
            $row['add_time'] = !empty($row['add_time']) ? $row['add_time'] : time();
            $item = array(
                'loc' => "$site_url" . $article_url,
                'lastmod' => $this->dateFormat($row['add_time'], 'Y-m-d') ,
                'changefreq' => "weekly",
                'priority' => "0.7",
            );
            $xml.= $this->siteMapItem($item);
        }
        $xml.= "</urlset>";
        @$fp = fopen("sitemap.xml", "w");
        if ($fp) {
            fwrite($fp, $xml);
            fclose($fp);
        }
    }
    public function rrs($cat_id = 0) {
        $site_url = $GLOBALS['host'];
        $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>
		<rss version=\"2.0\">
		<channel>";
        if ($cat_id == 0) {
            $xml.= "
			  <image>
			  <link>{$site_url}</link>
			  <url>http://localhost/ethnicharms2/templates/default/images/logo.png</url>
			  </image>
			  <title> {$GLOBALS['_CFG']['shop_name']} </title>
			  <description>{$GLOBALS['_CFG']['shop_desc']}</description>
			  <language>en-US</language>
			  <webMaster>service7@live.com</webMaster>
			  <ttl>5</ttl>
			  <pubDate>" . date('r') . "</pubDate>
			 ";
            $cats = $GLOBALS['Cate']->categoryAll();
            foreach ($cats as $key => $val) {
                $url = $site_url . '/' . $val['url'];
                $xml.= "
				<item>
				 <title><![CDATA[ {$val['cat_name']}]]></title>
				  <link>{$url}</link>
				  <guid>{$url}</guid>
				  <pubDate>" . date('r') . "</pubDate>
				  <description><![CDATA[ {$val['cat_desc']} ]]></description>
				 </item>";
            }
        } else {
        }
        $xml.= "</channel>
		</rss>";
        echo $xml;
        die();
    }
    private function rrsItem($item) {
        $items = "<url>\n";
        foreach ($item as $key => $val) {
            $items.= " <$key>" . $this->xmlencode($val, ENT_QUOTES) . "</$key>\n";
        }
        $items.= "</url>\n";
        return $items;
    }
    private function siteMapItem($item) {
        $items = "<url>\n";
        foreach ($item as $key => $val) {
            $items.= " <$key>" . $this->xmlencode($val, ENT_QUOTES) . "</$key>\n";
        }
        $items.= "</url>\n";
        return $items;
    }
    private function xmlencode($tag) {
        $tag = str_replace("&", "&amp;", $tag);
        $tag = str_replace("<", "&lt;", $tag);
        $tag = str_replace(">", "&gt;", $tag);
        $tag = str_replace("'", "&apos;", $tag);
        $tag = str_replace("\"", '&quot;', $tag);
        return $tag;
    }
    //取得时间段内每一天
    public function during($week) {
        $start = $week['start'];
        $end = $week['end'];
        $day_num = ceil(($end - $start) / (24 * 3600));
        $days = array();
        $day = array();
        for ($i = 0; $i < $day_num; $i++) {
            $per_day = ((24 * 3600) * $i);
            $day_start = strtotime(date("Y-m-d", $start)) + $per_day;
            $day_end = $day_start + (23 * 3600 + 3599);
            $day['start'] = $day_start;
            $day['end'] = $day_end;
            $days[] = $day;
        }
        return $days;
    }
    //取得时间段
    public function getDurDate($type = 'week') {
        $date = array();
        if ($type == 'week') {
            $date['start'] = mktime(0, 0, 0, date("m") , date("d") - date("w") + 1, date("Y"));
            $date['end'] = mktime(23, 59, 59, date("m") , date("d") - date("w") + 7, date("Y"));
        } elseif ($type == 'mon') {
            $date['start'] = mktime(0, 0, 0, date("m") , 1, date("Y"));
            $date['end'] = mktime(23, 59, 59, date("m") , date("t") , date("Y"));
        } elseif ($type == 'sea') {
            $getMonthDays = date("t", mktime(0, 0, 0, date('n') + (date('n') - 1) % 3, 1, date("Y")));
            $date['start'] = mktime(0, 0, 0, date('n') - (date('n') - 1) % 3, 1, date('Y'));
            $date['end'] = mktime(23, 59, 59, date('n') + (date('n') - 1) % 3, $getMonthDays, date('Y'));
        }
        return $date;
    }
    //设置linechart
    public function chartData($cats, $names, $datas) {
        $chart['cats'] = json_encode($cats);
        $ser = array();
        foreach ($names as $key => $val) {
            $ser[$key] = (array(
                'name' => $names[$key],
                'data' => $datas[$key]
            ));
        }
        $chart['series'] = json_encode($ser);
        $chart['count'] = count($cats);
        return $chart;
    }
    //csv读取
    public function getCsv($file_name, $start, $end) {
        $n = 0;
        $lines = array();
        $f = fopen($file_name, "r");
        if ($f) {
            while (!feof($f)) {
                ++$n;
                $line = fgetcsv($f);
                if (!is_array($line)) continue;
                foreach ($line as $key => $val) {
                    $line[$key] = iconv('gb2312', 'utf-8', $val);
                }
                if ($start <= $n) {
                    $lines[] = $line;
                }
                if ($end == $n) break;
            }
            fclose($f);
        }
        return $lines;
    }
    //清空数据
    public function truncateData() {
        $sql[] = " truncate table goods;";
        $sql[] = "truncate table goods_attr;";
        $sql[] = "truncate table goods_gallery;";
        $sql[] = "truncate table attribute;";
        $sql[] = "truncate table users;";
        $sql[] = "truncate table order_info;";
        $sql[] = "truncate table order_goods;";
        $sql[] = "truncate table user_address;";
        foreach ($sql as $key => $val) {
            mysql_query($val);
        }
    }
    //创建多级目录
    public function mkdirs($dir, $mod = 0700) {
        if (!is_dir($dir)) {
            if (!$this->mkdirs(dirname($dir),$mod)) {
                return false;
            }
			mkdir($dir, 0700);
            chmod($dir, 0700);
        }
        return true;
    }
    //搜索引擎蜘蛛
    public function isSpider() {
        $searchengine_bot = array(
            'googlebot',
            'mediapartners-google',
            'baiduspider+',
            'msnbot',
            'yodaobot',
            'yahoo! slurp;',
            'yahoo! slurp china;',
            'iaskspider',
            'sogou web spider',
            'sogou push spider'
        );
        $searchengine_name = array(
            'GOOGLE',
            'GOOGLE ADSENSE',
            'BAIDU',
            'MSN',
            'YODAO',
            'YAHOO',
            'Yahoo China',
            'IASK',
            'SOGOU',
            'SOGOU'
        );
        $spider = strtolower($_SERVER['HTTP_USER_AGENT']);
        foreach ($searchengine_bot AS $key => $value) {
            if (strpos($spider, $value) !== false) {
                $spider = $searchengine_name[$key];
                return $spider;
            }
        }
        return false;
    }
    //访问统计
    public function visit() {
        if (isset($_REQUEST['ajax'])) return false;
        /* 检查客户端是否存在访问统计的cookie */
        $visit_times = (!empty($_COOKIE['ETH']['visit_times'])) ? intval($_COOKIE['ETH']['visit_times']) + 1 : 1;
        setcookie('ETH[visit_times]', $visit_times, time() + 86400 * 365, '/');
        if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            $pos = strpos($_SERVER['HTTP_ACCEPT_LANGUAGE'], ';');
            $lang = addslashes(($pos !== false) ? substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, $pos) : $_SERVER['HTTP_ACCEPT_LANGUAGE']);
        } else {
            $lang = '';
        }
        /* 来源 */
        if (!empty($_SERVER['HTTP_REFERER']) && strlen($_SERVER['HTTP_REFERER']) > 9) {
            $pos = strpos($_SERVER['HTTP_REFERER'], '/', 9);
            if ($pos !== false) {
                $domain = substr($_SERVER['HTTP_REFERER'], 0, $pos);
                $path = substr($_SERVER['HTTP_REFERER'], $pos);
                /* 来源关键字 */
                if (!empty($domain) && !empty($path)) {
                    $res = $this->engineKeywords($domain, $path);
                    if ($res) {
                        $this->keywordsAdd($res);
                    }
                }
            } else {
                $domain = $path = '';
            }
        } else {
            $domain = $path = '';
        }
        $data['ip'] = $_SERVER['REMOTE_ADDR'];
        $data['add_time'] = time();
        $data['browser'] = $this->getBrowser();
        $data['os'] = $this->getOs();
        $data['lang'] = $lang;
        $data['refe_domain'] = $domain;
        $data['refe_url'] = $path;
        $data['local_url'] = $_SERVER['REQUEST_URI'];
        $table = 'stats_' . date("Ym", time());
        $sql = "CREATE TABLE IF NOT EXISTS `$table` (
		  `id` int(10) NOT NULL AUTO_INCREMENT,
		  `ip` varchar(32) NOT NULL,
		  `add_time` int(10) NOT NULL COMMENT '访问时间',
		  `browser` varchar(60) NOT NULL,
		  `os` varchar(255) NOT NULL,
		  `lang` varchar(20) NOT NULL,
		  `refe_domain` varchar(100) NOT NULL COMMENT '来路域名',
		  `refe_url` varchar(255) NOT NULL COMMENT '来路url',
		  `local_url` varchar(255) NOT NULL COMMENT '本地url',
		  PRIMARY KEY (`id`)
		) ENGINE=InnoDB  DEFAULT CHARSET=utf8  ;

		";

        if (mysql_query($sql)) {
            $GLOBALS['db']->autoExecute($table, $data);
        }
    }
    //取得搜索引擎的关键词
    public function engineKeywords($domain, $path) {
        $res = array();
        if (strpos($domain, 'google.com.tw') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) {
            $searchengine = 'GOOGLE TAIWAN';
            $keywords = urldecode($regs[1]); // google taiwan

        }
        if (strpos($domain, 'google.cn') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) {
            $searchengine = 'GOOGLE CHINA';
            $keywords = urldecode($regs[1]); // google china

        }
        if (strpos($domain, 'google.com') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) {
            $searchengine = 'GOOGLE';
            $keywords = urldecode($regs[1]); // google

        } elseif (strpos($domain, 'baidu.') !== false && preg_match('/wd=([^&]*)/i', $path, $regs)) {
            $searchengine = 'BAIDU';
            $keywords = urldecode($regs[1]); // baidu

        } elseif (strpos($domain, 'baidu.') !== false && preg_match('/word=([^&]*)/i', $path, $regs)) {
            $searchengine = 'BAIDU';
            $keywords = urldecode($regs[1]); // baidu

        } elseif (strpos($domain, '114.vnet.cn') !== false && preg_match('/kw=([^&]*)/i', $path, $regs)) {
            $searchengine = 'CT114';
            $keywords = urldecode($regs[1]); // ct114

        } elseif (strpos($domain, 'iask.com') !== false && preg_match('/k=([^&]*)/i', $path, $regs)) {
            $searchengine = 'IASK';
            $keywords = urldecode($regs[1]); // iask

        } elseif (strpos($domain, 'soso.com') !== false && preg_match('/w=([^&]*)/i', $path, $regs)) {
            $searchengine = 'SOSO';
            $keywords = urldecode($regs[1]); // soso

        } elseif (strpos($domain, 'sogou.com') !== false && preg_match('/query=([^&]*)/i', $path, $regs)) {
            $searchengine = 'SOGOU';
            $keywords = urldecode($regs[1]); // sogou

        } elseif (strpos($domain, 'so.163.com') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) {
            $searchengine = 'NETEASE';
            $keywords = urldecode($regs[1]); // netease

        } elseif (strpos($domain, 'yodao.com') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) {
            $searchengine = 'YODAO';
            $keywords = urldecode($regs[1]); // yodao

        } elseif (strpos($domain, 'zhongsou.com') !== false && preg_match('/word=([^&]*)/i', $path, $regs)) {
            $searchengine = 'ZHONGSOU';
            $keywords = urldecode($regs[1]); // zhongsou

        } elseif (strpos($domain, 'search.tom.com') !== false && preg_match('/w=([^&]*)/i', $path, $regs)) {
            $searchengine = 'TOM';
            $keywords = urldecode($regs[1]); // tom

        } elseif (strpos($domain, 'live.com') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) {
            $searchengine = 'MSLIVE';
            $keywords = urldecode($regs[1]); // MSLIVE

        } elseif (strpos($domain, 'tw.search.yahoo.com') !== false && preg_match('/p=([^&]*)/i', $path, $regs)) {
            $searchengine = 'YAHOO TAIWAN';
            $keywords = urldecode($regs[1]); // yahoo taiwan

        } elseif (strpos($domain, 'cn.yahoo.') !== false && preg_match('/p=([^&]*)/i', $path, $regs)) {
            $searchengine = 'YAHOO CHINA';
            $keywords = urldecode($regs[1]); // yahoo china

        } elseif (strpos($domain, 'yahoo.') !== false && preg_match('/p=([^&]*)/i', $path, $regs)) {
            $searchengine = 'YAHOO';
            $keywords = urldecode($regs[1]); // yahoo

        } elseif (strpos($domain, 'msn.com.tw') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) {
            $searchengine = 'MSN TAIWAN';
            $keywords = urldecode($regs[1]); // msn taiwan

        } elseif (strpos($domain, 'msn.com.cn') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) {
            $searchengine = 'MSN CHINA';
            $keywords = urldecode($regs[1]); // msn china

        } elseif (strpos($domain, 'msn.com') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) {
            $searchengine = 'MSN';
            $keywords = urldecode($regs[1]); // msn

        }
        if (!empty($keywords)) {
            $gb_search = array(
                'YAHOO CHINA',
                'TOM',
                'ZHONGSOU',
                'NETEASE',
                'SOGOU',
                'SOSO',
                'IASK',
                'CT114',
                'BAIDU'
            );
            if (CHARSET == 'utf-8' && in_array($searchengine, $gb_search)) {
                $keywords = ecs_iconv('GBK', 'UTF8', $keywords);
            }
            if (CHARSET == 'gbk' && !in_array($searchengine, $gb_search)) {
                $keywords = ecs_iconv('UTF8', 'GBK', $keywords);
            }
            $res['engine'] = $searchengine;
            $res['keywords'] = $keywords;
        }
        return $res;
    }
    //取得浏览器版本
    public function getBrowser() {
        if (empty($_SERVER['HTTP_USER_AGENT'])) {
            return '';
        }
        $agent = $_SERVER['HTTP_USER_AGENT'];
        $browser = '';
        $browser_ver = '';
        if (preg_match('/MSIE\s([^\s|;]+)/i', $agent, $regs)) {
            $browser = 'Internet Explorer';
            $browser_ver = $regs[1];
        } elseif (preg_match('/FireFox\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'FireFox';
            $browser_ver = $regs[1];
        } elseif (preg_match('/Maxthon/i', $agent, $regs)) {
            $browser = '(Internet Explorer ' . $browser_ver . ') Maxthon';
            $browser_ver = '';
        } elseif (preg_match('/Opera[\s|\/]([^\s]+)/i', $agent, $regs)) {
            $browser = 'Opera';
            $browser_ver = $regs[1];
        } elseif (preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs)) {
            $browser = 'OmniWeb';
            $browser_ver = $regs[2];
        } elseif (preg_match('/Netscape([\d]*)\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'Netscape';
            $browser_ver = $regs[2];
        } elseif (preg_match('/safari\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'Safari';
            $browser_ver = $regs[1];
        } elseif (preg_match('/NetCaptor\s([^\s|;]+)/i', $agent, $regs)) {
            $browser = '(Internet Explorer ' . $browser_ver . ') NetCaptor';
            $browser_ver = $regs[1];
        } elseif (preg_match('/Lynx\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'Lynx';
            $browser_ver = $regs[1];
        }
        if (!empty($browser)) {
            return addslashes($browser . ' ' . $browser_ver);
        } else {
            return $agent;
        }
    }
    //取得操作系统
    public function getOs() {
        if (empty($_SERVER['HTTP_USER_AGENT'])) {
            return 'Unknown';
        }
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        $os = '';
        if (strpos($agent, 'win') !== false) {
            if (strpos($agent, 'nt 5.1') !== false) {
                $os = 'Windows XP';
            } elseif (strpos($agent, 'nt 5.2') !== false) {
                $os = 'Windows 2003';
            } elseif (strpos($agent, 'nt 5.0') !== false) {
                $os = 'Windows 2000';
            } elseif (strpos($agent, 'nt 6.0') !== false) {
                $os = 'Windows Vista';
            } elseif (strpos($agent, 'nt') !== false) {
                $os = 'Windows NT';
            } elseif (strpos($agent, 'win 9x') !== false && strpos($agent, '4.90') !== false) {
                $os = 'Windows ME';
            } elseif (strpos($agent, '98') !== false) {
                $os = 'Windows 98';
            } elseif (strpos($agent, '95') !== false) {
                $os = 'Windows 95';
            } elseif (strpos($agent, '32') !== false) {
                $os = 'Windows 32';
            } elseif (strpos($agent, 'ce') !== false) {
                $os = 'Windows CE';
            }
        } elseif (strpos($agent, 'linux') !== false) {
            $os = 'Linux';
        } elseif (strpos($agent, 'unix') !== false) {
            $os = 'Unix';
        } elseif (strpos($agent, 'sun') !== false && strpos($agent, 'os') !== false) {
            $os = 'SunOS';
        } elseif (strpos($agent, 'ibm') !== false && strpos($agent, 'os') !== false) {
            $os = 'IBM OS/2';
        } elseif (strpos($agent, 'mac') !== false && strpos($agent, 'pc') !== false) {
            $os = 'Macintosh';
        } elseif (strpos($agent, 'powerpc') !== false) {
            $os = 'PowerPC';
        } elseif (strpos($agent, 'aix') !== false) {
            $os = 'AIX';
        } elseif (strpos($agent, 'hpux') !== false) {
            $os = 'HPUX';
        } elseif (strpos($agent, 'netbsd') !== false) {
            $os = 'NetBSD';
        } elseif (strpos($agent, 'bsd') !== false) {
            $os = 'BSD';
        } elseif (strpos($agent, 'osf1') !== false) {
            $os = 'OSF1';
        } elseif (strpos($agent, 'irix') !== false) {
            $os = 'IRIX';
        } elseif (strpos($agent, 'freebsd') !== false) {
            $os = 'FreeBSD';
        } elseif (strpos($agent, 'teleport') !== false) {
            $os = 'teleport';
        } elseif (strpos($agent, 'flashget') !== false) {
            $os = 'flashget';
        } elseif (strpos($agent, 'webzip') !== false) {
            $os = 'webzip';
        } elseif (strpos($agent, 'offline') !== false) {
            $os = 'offline';
        }
		elseif (strpos($agent, 'android') !== false) {
            $os = 'android';
        }
		elseif (strpos($agent, 'iphone') !== false) {
            $os = 'iphone';
        }
		elseif (strpos($agent, 'blackberry') !== false) {
            $os = 'blackberry';
        }
		elseif (strpos($agent, 'googlebot') !== false) {
            $os = 'googlebot';
        }
		elseif (strpos($agent, 'yahoo') !== false) {
            $os = 'yahoo';
        }
		elseif (strpos($agent, 'bingbot') !== false) {
            $os = 'bingbot';
        }

		else {
            $os = $agent;
        }

        return $os;
    }
    //增加关键词到数据库
    public function keywordsAdd($data) {
        $engine = $data['engine'];
        $keywords = $data['keywords'];
        if ($engine && $keywords) {
            $one = $this->counts("select count(*) from keywords where keyword='" . $keywords . "'");
            if ($one) {
                $sql = "update keywords set times=times+1 where keyword='" . $keywords . "'";
            } else {
                $sql = "insert into keywords (`engine`,`keyword`) values('" . $engine . "','" . $keywords . "')";
            }
            return mysql_query($sql);
        }
        return false;
    }
	//备份数据库
	public function backupSql(){
		$mysql = "set charset utf8;\r\n";
		$q1 = mysql_query("show tables");
		while ($t = mysql_fetch_array($q1))
		{
			$table = $t[0];
			$q2 = mysql_query("show create table `$table`");
			$sql = mysql_fetch_array($q2);

			$mysql .= $sql['Create Table'] . ";\r\n";

			$q3 = mysql_query("select * from `$table`");
			while ($data = mysql_fetch_assoc($q3))
			{
				$keys = array_keys($data);
				$keys = array_map('addslashes', $keys);
				$keys = join('`,`', $keys);
				$keys = "`" . $keys . "`";
				$vals = array_values($data);
				$vals = array_map('addslashes', $vals);
				$vals = join("','", $vals);
				$vals = "'" . $vals . "'";
				$mysql .= "insert into `$table`($keys) values($vals);\r\n";
			}
		}
		$name = $GLOBALS['_CFG']['shop_name'] .'-'. date('Y-m-d-h-i-s') . ".sql";
		$path = './temp/backup/'.$name;


		$fp = fopen($path, 'w');
		fputs($fp, $mysql);
		fclose($fp);
		$zip = $this->zip($path);
		if($zip)
		{
			unlink($path);
			die($name);
		}
		die('0');

	}
	//压缩文件
	public function zip($path,$new_path=''){

		$new_path = !empty($new_path) ?  $new_path : $path.'.zip';
		require(INC_PATH."/class/pclzip.lib.php");
		$archive = new PclZip($new_path);
		$v_list = $archive->create($path);
		return $v_list;

	}
	//移动设备
	public function isMobileDevice(){
		$ua = strtolower($_SERVER['HTTP_USER_AGENT']);

		$uachar = "/(nokia|sony|ericsson|mot|samsung|sgh|lg|philips|panasonic|alcatel|lenovo|cldc|midp|mobile|android)/i";

		if(($ua == '' || preg_match($uachar, $ua))&& !strpos(strtolower($_SERVER['REQUEST_URI']),'wap'))
		{
			return true;
		}
		return false;
	}
	//匹配锚文本
	public function anchorMatch(){

	}

	//取得最近搜索
	public function recentSearch(){
		$relate_words = !empty($_SESSION['search']['relate_words']) ? $_SESSION['search']['relate_words'] : array();
		$i=0;
		foreach($relate_words as $key=>$val)
		{
			setcookie("recent_search[$i]",$key,strtotime("+1 years"),'/ ');
			$i++;
		}
		$rec_search = @$_COOKIE['recent_search'];
		if($rec_search)
		{
			$rec_search = array_reverse($rec_search);
		}
		return $rec_search;

	}

	//限制访问
	public function denyVisit(){
		if(empty($_SESSION["root"]))
		{
			$_SESSION['root'] = !empty($_GET['root']) ? $_GET['root'] : '';
		}


		//访问限制
		if(preg_match("/zh-cn/i",$_SERVER['HTTP_ACCEPT_LANGUAGE']) && empty($_SESSION['root']))
		{

			return true;
		}
		return false;

	}


	//全站数据统计
	public function statCounts(){
		$jf = JF_MALL_ID;
		$res['cat_count']   = $this->counts("select count(*) from category where cat_id!=$jf");
		$res['goods_count'] = $this->counts("select count(*) from goods where cat_id!=$jf");
		$res['user_count']  = $this->counts("select count(*) from users where cat_id!=$jf");
		$res['format'] = $this->numStrFormat($res);

		return $res;
	}

	public function numStrFormat($res){
		$r = array();
		foreach($res as $key=>$val)
		{
			$v = sprintf("%05d",$val);

			$r[$key] = preg_replace("/(\d)/","<em>$1</em>",$v);
		}
		//print_r($r);
		//die();
		return $r;
	}

	//删除文件
	public function unlinks($arr){
		foreach($arr as $key=>$val)
		{
			if(file_exists($val))
			{
				unlink($val);
			}
		}
	}


}
?>



